package com.fq.web.controller;

import com.fq.client.domain.CourseDO;
import com.fq.client.service.CourseService;
import com.fq.web.convertor.CourseConverter;
import com.fq.web.domain.CourseVO;
import com.fq.web.domain.JavisResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jifang
 * @since 16/2/29 下午5:50.
 */
@Controller
@RequestMapping("/course")
public class CourseController {

    @Autowired
    private CourseService service;

    @ResponseBody
    @RequestMapping("/add_course.do")
    public JavisResult<Integer> addCourse(@RequestParam(value = "t_id") Integer tId,
                                          String name, Integer credit) {
        CourseDO course = new CourseDO();
        course.settId(tId);
        course.setName(name);
        course.setCredit(credit);
        Integer cId = service.addCourse(course);
        return new JavisResult<>(cId);
    }

    @ResponseBody
    @RequestMapping("/get_course_by_t_id.do")
    public JavisResult<List<CourseVO>> getCourseByTId(@RequestParam(value = "t_id") Integer tId) {
        List<CourseDO> courses = service.getCourseByTId(tId);
        return new JavisResult<>(courseListConvert(courses));
    }

    @ResponseBody
    @RequestMapping("/get_all_course.do")
    public JavisResult<List<CourseVO>> getAllCourse() {
        List<CourseDO> courses = service.getAllCourse();
        return new JavisResult<>(courseListConvert(courses));
    }

    @ResponseBody
    @RequestMapping("/get_course_by_credit.do")
    public JavisResult<List<CourseVO>> getCourseByCredit(Integer credit) {
        List<CourseDO> courses = service.getCourseByCredit(credit);
        return new JavisResult<>(courseListConvert(courses));
    }

    private List<CourseVO> courseListConvert(List<CourseDO> courses) {
        List<CourseVO> output = new ArrayList<>();
        if (courses != null) {
            for (CourseDO course : courses) {
                output.add(CourseConverter.converter.convert(course));
            }
        }
        return output;
    }
}
